<template>
  <view class="cell-item" @click="handleChange">
    <slot v-if="$slots.default"></slot>
    <view v-else>{{ label }}</view>
    <view class="radio" v-if="!getCheckedFlag()"></view>
    <view v-if="getCheckedFlag()" class="radio radio-checked">
      <u-icon name="checkbox-mark"></u-icon>
    </view>

  </view>
</template>
<script lang="ts" setup>
import { Ref, inject, computed, nextTick } from 'vue';
const emit = defineEmits(['change', 'update:value']);
const handleChange = () => {
  nextTick(() => {
    if (props.disabled) {
      return;
    }
    model.value = props.value;
    emit('change', model.value);
  });
};
const props = defineProps<{
  value?: string | number | undefined;
  label?: string | number;
  disabled?: boolean;
}>();
type RadioGroupModelValue = {
  type: 'radio' | 'multiple';
  groupModelValue: Ref<string | number | string[] | number[]>;
  updateRadioGroupModelValue: Function;
};
const injectData: RadioGroupModelValue | undefined = inject(
  'radioGroupModelValue'
);
const {
  groupModelValue,
  updateRadioGroupModelValue,
  type: radioType,
} = injectData || {};
const model = computed({
  get() {
    return groupModelValue ? groupModelValue.value : props.value;
  },
  set(val) {
    // if (radioGroupModelValue?.value) {
    emit('update:value', val);
    return updateRadioGroupModelValue!(val);
    // }
  },
});
const getCheckedFlag = () => {
  if (!model.value && !props.value) {
    return true;
  }
  if (radioType) {
    return radioType === 'radio'
      ? model.value === props.value
      : (model.value as (string | number | undefined)[] | undefined)?.includes(
          props.value
        );
  }
  return model.value === props.value;
};
</script>
<style lang="scss">
.cell-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  line-height: 80rpx;
  border-bottom: 1px solid #eee;
}
.radio {
  width: 40rpx;
  height: 40rpx;
  border-radius: 30rpx;
  border: 1px solid #ccc;
  line-height: 40rpx;
  text-align: center;
}

.radio-checked {
  color: #fff;
  background-color: $u-type-primary;
  border: 1px solid $u-type-primary;
}
.radio-checked::after {
  content: '√';
}
</style>
